/*
 * Copyright 2014-2026 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wzq.framework.mvc;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.SimpleTypeConverter;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.util.Assert;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;

import com.wzq.framework.util.UtilJson;

/**
 * @author <a href="mailto:yanghao@0easy.com">杨浩</a>
 */
public class ApiHandlerMethod {
	private static final ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
	private static final SimpleTypeConverter converter = new SimpleTypeConverter();
	protected final Logger logger = LogManager.getLogger(getClass());
	private final Object bean;
	private final Method method;
	private final MethodParameter[] params;
	
	
	public ApiHandlerMethod(Object bean, Method method) {
		Assert.notNull(bean, "bean == null");
		Assert.notNull(method, "method == null");
		this.bean = bean;
		this.method = method;

		int len = method.getParameterTypes().length;
		params = new MethodParameter[len];
		for (int i = 0; i < len; i++) {
			params[i] = new MethodParameter(method, i);
			params[i].initParameterNameDiscovery(parameterNameDiscoverer);
		}
	}

	
	public Object invokeForRequest(ServletWebRequest servletWebRequest) throws Exception {
		Object[] args = getMethodArgumentValues(servletWebRequest);
		if (logger.isTraceEnabled()) logger.trace("method={}.{}, args={}", bean.getClass().getSimpleName(), method.getName(), Arrays.asList(args));
		
		Object returnValue = doInvoke(args);
		if (logger.isTraceEnabled()) logger.trace("method={} return=[{}]", method.getName(), returnValue);
		return returnValue;
	}
	
	/** 提取调用参数的值 */
	private Object[] getMethodArgumentValues(NativeWebRequest request) throws Exception {
		Object[] args = new Object[params.length];
		for (int i = 0, len = params.length; i < len; i++) {
			args[i] = resolveArgument(params[i], request);
		}
		return args;
	}
	
	/** 从webRequest中提取参数值 */
	private Object resolveArgument(MethodParameter param, NativeWebRequest webRequest) throws Exception {
		return convert(UtilApiHandlerMethod.resolveName(param, webRequest), param);
	}

	private Object convert(Object value, MethodParameter param) {
		final Class<?> type = param.getParameterType();
		
		if (!type.isPrimitive()) {
			if (value == null || type.isInstance(value)) return value;
			
			if (value instanceof String) {
				String str = (String) value;
				if (str.length() >= 2) {
					char first = str.charAt(0), end = str.charAt(str.length() - 1);
					
					if (first == '{' && end == '}') {
						Type ptype = param.getGenericParameterType();
						if (ptype instanceof ParameterizedType) {
							ParameterizedType gptype = (ParameterizedType) ptype;
							Type[] types = gptype.getActualTypeArguments();
							List<Class<?>> parameterClasses = new ArrayList<>(); 
							for (Type tmp : types) {
								if ("?".equals(tmp.getTypeName())) {
									parameterClasses.add(Object.class);
								} else {
									parameterClasses.add((Class<?>) tmp);
								}
							}
							return UtilJson.readValue(str, (Class<?>) gptype.getRawType(), (Class<?>) gptype.getRawType(), parameterClasses.toArray(new Class<?>[0]));
						}
						return UtilJson.convertValue(str, type);
					}
					
					if (first == '[' && end == ']') {
						Type ptype = param.getGenericParameterType();
						if (ptype instanceof ParameterizedType) {
							ParameterizedType gptype = (ParameterizedType) ptype;
							Type[] types = gptype.getActualTypeArguments();
							if (types.length > 0 && !"?".equals(types[0].getTypeName())) {
								return UtilJson.readValue(str, (Class<?>) gptype.getRawType(), (Class<?>)types[0]);
							}
						}
						return UtilJson.convertValue(str, type);
					}
				}
			}
		}
		
		return converter.convertIfNecessary(value, type, param);
	}
	
	private Object doInvoke(Object... args) throws Exception {
		try {
			return method.invoke(bean, args);
		} catch (InvocationTargetException ex) {
			Throwable targetException = ex.getTargetException();
			if (targetException instanceof Exception) {
				throw (Exception) targetException;
			} else if (targetException instanceof Error) {
				throw (Error) targetException;
			} else {
				throw new IllegalStateException(ex.getMessage(), targetException);
			}
		}
	}
}

